package cn.com.nes.site.service.system.role.impl;

import cn.com.nes.mybatis.agent.ope.entity.IsRoleInfo;
import cn.com.nes.mybatis.agent.ope.entity.IsRoleModelInfo;
import cn.com.nes.mybatis.agent.ope.mapper.IsRoleInfoMapper;
import cn.com.nes.mybatis.agent.ope.mapper.IsRoleModelInfoMapper;
import cn.com.nes.site.entity.vo.role.SaveRoleInfoVo;
import cn.com.nes.site.service.system.role.RoleInfoService;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 角色管理
 *
 * @Author: ShenWei
 * @Date: 2024/03/07/19:08
 */
@Service
public class RoleInfoServiceImpl implements RoleInfoService {

    private static final String sjly = "agent"; // 数据来源

    @Resource
    IsRoleInfoMapper roleInfoMapper;

    @Resource
    IsRoleModelInfoMapper roleModelInfoMapper;

    /**
     * 保存角色信息
     * @param vo  角色实体
     * @param manufactureId   厂商id
     * @return
     * @throws Exception
     */
    @Override
    public String saveRoleInfo(SaveRoleInfoVo vo, String manufactureId) throws Exception {
        int result;
        IsRoleInfo roleInfo;
        //新增或编辑时,判断角色是否重复
        String roleName = roleInfoMapper.selectRoleName(vo, manufactureId);
        if (StrUtil.isNotEmpty(roleName)) {
            throw new Exception("该角色名称已存在,请重新编辑");
        }
        //角色id为空,新增;不为空,编辑
        if (StrUtil.isEmpty(vo.getRoleId())) {
            roleInfo = new IsRoleInfo();
            roleInfo.setManufactureId(manufactureId);
            roleInfo.setSfsc((byte) 0);
            roleInfo.setSjly(sjly);
            roleInfo.setEnabled((byte) 1);
            roleInfo.setCreatorId(vo.getUserId());
            //创建角色id
            String createRoleId = "role_" + UUID.randomUUID().toString();
            roleInfo.setRoleId(createRoleId);
        } else {
            //根据角色id查找角色信息
            roleInfo = roleInfoMapper.selectRoleInfoByRoleId(vo.getRoleId(), manufactureId);
        }
        //前端传来的权限(模块码)不为空,则进行角色权限操作
        handelRoleModel(vo, roleInfo, manufactureId);
        //角色权限操作完成后,进行角色的数据封装
        roleInfo.setName(vo.getName());
        roleInfo.setDesc(vo.getDesc());
        if (StrUtil.isEmpty(vo.getRoleId())) {
            //新增
            result = roleInfoMapper.insert(roleInfo);
            if (0 == result) {
                throw new Exception("新增角色信息失败");
            }
            return roleInfo.getRoleId();
        } else {
            //更新数据来源
            roleInfo.setSjly(sjly);
            //更新
            result = roleInfoMapper.updateByRoleId(roleInfo);
            if (0 == result) {
                throw new Exception("编辑角色信息失败");
            }
            return roleInfo.getRoleId();
        }
    }

    /**
     * 编辑角色时,处理角色权限
     *
     * @param vo            {@link SaveRoleInfoVo}
     * @param roleInfo      {@link IsRoleInfo}
     * @param manufactureId 厂商id
     */
    @Transactional(rollbackFor = Exception.class)
    public void handelRoleModel(SaveRoleInfoVo vo, IsRoleInfo roleInfo, String manufactureId) {
        String privilege = vo.getPcqx() + "," + vo.getAppqx();
        //去除末尾逗号
        if (privilege.charAt(privilege.length() - 1) == ',') {
            privilege = privilege.substring(0, privilege.length()-1);
        }
        if (StrUtil.isNotEmpty(privilege)) {
            //将String类型的模块码集合,转成list
            List<String> listQx = Arrays.asList(privilege.split(","));
            //向角色模块关联表中,新增/编辑数据
            //根据角色id,删除已存在的角色模块ids
            roleModelInfoMapper.deleteModelFunctionByRoleId(roleInfo.getRoleId());
            //解析出modelid对应的code
            String modelId="";
            String codes="";
            byte isAdd=1;
            for (String modelId_code:listQx) {
                String code="";
                if(modelId_code.indexOf(";")>-1){//如果包含;说明存在对应的子功能
                    modelId=modelId_code.substring(0,modelId_code.indexOf(";"));
                    codes=modelId_code.substring(modelId_code.indexOf(";")+1,modelId_code.length());
                    if(codes.indexOf("*")>-1){
                        String[] codeArray=codes.split("\\*");
                        for (String codeStr:codeArray) {
                            code=codeStr;
//                            isAdd=1;
                            insertRoleModel(roleInfo,manufactureId,modelId,code,isAdd);//isAdd为1，说明修改过子权限
                        }
                    }else{
                        code=codes;
                        insertRoleModel(roleInfo,manufactureId,modelId,code, isAdd);
                    }
                }else{
                    modelId=modelId_code;
                    insertRoleModel(roleInfo,manufactureId,modelId,code,isAdd);
                }

            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void insertRoleModel(IsRoleInfo roleInfo, String manufactureId,String modelId,String code,byte isAdd) {
        IsRoleModelInfo roleModelInfo = new IsRoleModelInfo();
        //创建角色模块功能id
        String roleModelFunctionId = "rmRel_" + UUID.randomUUID().toString();
        //封装数据
        roleModelInfo.setRoleModelFunctionId(roleModelFunctionId);
        roleModelInfo.setManufactureId(manufactureId);
        roleModelInfo.setRoleId(roleInfo.getRoleId());
        roleModelInfo.setFunctionId(code);
        //根据功能id,获取模块id(因为多个功能id,会对应一个模块)
        roleModelInfo.setModelId(modelId);
        roleModelInfo.setSfsc((byte) 0);
        roleModelInfo.setSjly(sjly);
        roleModelInfo.setIsAdd(isAdd);//添加过子权限
        roleModelInfoMapper.insert(roleModelInfo);
    }
}
